<template>
  <div class="user_is_not-found" v-if="profileData.id === null">
    没有该用户嘞
  </div>
  <div v-else-if="profileData">
    <el-container class="profile-layout">
      <el-header class="profile-header" :style="backgroundStyle">
        <div class="profile-info">
          <el-avatar class="profile-avatar" :src="profileData.profilePicture || 'https://i.pravatar.cc/100'"
            size="large"></el-avatar>
          <div class="user-details">
            <div class="username-level">
              <h2>{{ profileData.username }}</h2>
              <el-tag :type="profileData.isVip ? 'warning' : 'success'">
                LV{{ profileData.level }}
              </el-tag>
            </div>
            <p>{{ profileData.bio || '这是你的曼波签名！' }}</p>
          </div>
        </div>
        <div class="follow-section" v-if="!isOwnProfile">
          <el-button type="primary" @click="toggleFollow">
            {{ isFollowing ? '取消关注' : '关注此人' }}
          </el-button>
        </div>
      </el-header>

      <!-- Navigation Tabs and Stats on the Same Row -->
      <el-header class="navigation-and-stats">
        <div class="navigation-tabs">
          <el-menu mode="horizontal" :default-active="activeTab" :ellipsis="false" class="tab-menu">
            <el-menu-item index="homePage" @click="setActiveTab('homePage')">
              <House /> 主页
            </el-menu-item>
            <el-menu-item index="posts" @click="setActiveTab('posts')">
              <DataAnalysis /> 投稿
            </el-menu-item>
            <el-menu-item index="favorites" @click="setActiveTab('favorites')">
              <Folder /> 收藏
            </el-menu-item>
            <el-menu-item index="likes" @click="setActiveTab('likes')">
              <Star /> 点赞
            </el-menu-item>
            <el-menu-item index="products" @click="setActiveTab('products')">
              <Picture /> 个人商品
            </el-menu-item>
          </el-menu>
        </div>

        <!-- Stats as Hyperlinks -->
        <div class="profile-stats">
          <a href="#" class="stat-item"  @click="setActiveTab('follow')">
            <span>关注数</span>
            <p>{{ profileData.followCount }}</p>
          </a>
          <a href="#" class="stat-item"  @click="setActiveTab('fans')">
            <span>粉丝数</span>
            <p>{{ profileData.fanCount }}</p>
          </a>
          <a href="#" class="stat-item">
            <span>文章数</span>
            <p>{{ profileData.postCount }}</p>
          </a>
          <a href="#" class="stat-item">
            <span>小说数</span>
            <p>{{ profileData.novelCount }}</p>
          </a>
        </div>

      </el-header>
    </el-container>

    <!-- Display the component based on the active tab -->
    <el-container class="wrapper">
      <homePage v-if="activeTab === 'homePage'" :user-id="userId"></homePage>
      <followSidenav v-if="activeTab === 'follow'" :user-id="userId"></followSidenav>
      <postList v-if="activeTab === 'posts'" :user-id="userId"></postList>
      <favoriteList v-if="activeTab === 'favorites'" :user-id="userId"></favoriteList>
      <likeList v-if="activeTab === 'likes'" :user-id="userId"></likeList>
      <productList v-if="activeTab === 'products'" :user-id="userId"></productList>
    </el-container>
  </div>
</template>


<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { House, DataAnalysis, Folder, Star, Picture } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRoute } from 'vue-router';
import homePage from './components/homePage.vue';
import followSidenav from './components/follow-sidenav.vue';


import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const route = useRoute();
const userId = route.params.id;
const currentUserId = ref(userStore.userInfo.id);

// Track the active tab
const activeTab = ref('homePage');


function setActiveTab(tab: string) {
  if (!isOwnProfile.value && (tab === 'follow' || tab === 'fans')) {
    ElMessage.error('只能查看自己的列表');
    return;
  }
  activeTab.value = tab;
}

// User profile data
const profileData = ref({
  id: null,
  username: 'null',
  followCount: 0,
  fanCount: 0,
  profilePicture: null,
  backgroundPicture: null,
  email: 'newuser@example.com',
  bio: null,
  level: 1,
  isVip: false,
  postCount: 0,
  novelCount: 0,
});

// Determine if viewing own profile
const isOwnProfile = computed(() => profileData.value.id === currentUserId.value);

// Follow state
const isFollowing = ref(false);

onMounted(() => {
  // Fetch profile data
  axios.get(`/api/users/${userId}`)
    .then(response => {
      if (response.data.code !== 200) {
        ElMessage.error(response.data.msg);
        return;
      }
      profileData.value = response.data.data;

      // Check if current user is following the profile user
      if (!isOwnProfile.value) {
        checkFollowStatus();
      }
    })
    .catch(error => {
      console.error('Error fetching profile data:', error);
    });
});

// Check follow status
function checkFollowStatus() {
  axios.get(`/api/users/isFollow?userId=${currentUserId.value}&followId=${userId}`)
    .then(response => {
      if (response.data.code === 200) {
        isFollowing.value = response.data.data;
      } else {
        ElMessage.error('Failed to get follow status');
      }
    })
    .catch(error => console.error('Error checking follow status:', error));
}

// Toggle follow/unfollow
function toggleFollow() {
  isFollowing.value = !isFollowing.value;
  if (isFollowing.value) {
    profileData.value.followCount++; // 增加关注数
    ElMessage({
      message: '关注成功',
      type: 'success',
    });
  } else {
    profileData.value.followCount--; // 减少关注数
    ElMessage({
      message: '你已经取消关注',
      type: 'warning',
    });
  }
}

// Dynamic background style
const backgroundStyle = computed(() => ({
  backgroundImage: `url(${profileData.value.backgroundPicture})`,
  backgroundSize: 'cover',
  backgroundPosition: 'center'
}));

</script>


<style scoped>
/* Basic container layout */
.profile-layout {

  width: 90%;
  margin: auto;
  position: relative;
}

/* Profile Header */
.profile-header {
  display: flex;
  height: 200px;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ddd;
}

.profile-info {
  display: flex;
  align-items: center;
}

.profile-avatar {
  margin-right: 20px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username-level {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username-level h2 {
  margin: 0;
  font-size: 20px;
}

/* Navigation Tabs and Stats in the Same Row */
.navigation-and-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--bPageBgColor);
  padding: 15px 30px;
  border-bottom: 1px solid #ddd;
}

.navigation-tabs {
  display: flex;
}

.tab-menu {
  font-size: 14px;
  /* 确保菜单项显示正常 */
  line-height: 66px;
  vertical-align: middle;
  margin-right: 16px;
}

/* Profile Stats as Hyperlinks */
.profile-stats {
  display: flex;
  gap: 40px;
}

.stat-item {
  text-align: center;
  color: #666;
  text-decoration: none;
  font-size: 14px;
}

.stat-item span {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: var(--bTextColor);
}

.stat-item p {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color:  var(--bTextColor);
}

.stat-item:hover {
  color: #00aaff;
}

.wrapper {
  min-height: 500px;
  width: 90%;
  margin: auto;
  background-color: var(--bPageBgColor);
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);

}

/* Follow/Unfollow button section */
.follow-section {
  position: absolute;
  right: 40px;
  top: calc(50% - 30px);

  margin-top: 0;
}
</style>
